package cn.zebra.dev.product.module.group.service.impl;

import cn.zebra.dev.common.utils.DateUtils;
import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.ibatis.plus.utils.Query;
import cn.zebra.dev.product.module.group.dao.GroupDao;
import cn.zebra.dev.product.module.group.entity.GroupEntity;
import cn.zebra.dev.product.module.group.service.GroupService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class GroupServiceImpl extends ServiceImpl<GroupDao, GroupEntity> implements GroupService {

    @Override
    public PageUtils<GroupEntity> findPage(Map<String, Object> params) {
        QueryWrapper<GroupEntity> wrapper = new QueryWrapper<>();
        IPage<GroupEntity> page = this.page(
                new Query<GroupEntity>(params).getPage(),
                wrapper
        );

        return new PageUtils<>(page);
    }

    @Override
    public boolean saveProductGroup(GroupEntity entity, Long createId) {
        isParent(entity);
        entity.setCreateId(createId);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateId(0L);
        entity.setUpdateTime(DateUtils.defaultTime());
        entity.setDeleteFlag(false);
        return save(entity);
    }

    private void isParent(GroupEntity entity) {
        Long parentId = entity.getParentId();
        if (parentId != null && parentId != 0L) {
            if (!isEntity(parentId)) {
                throw new RuntimeException("上级分组不存在!");
            }
        }
    }

    /**
     * 根据分组id查找分组是否存在
     *
     * @param id 分组id
     * @return 存在返回True 不存在返回False
     */
    @Override
    public Boolean isEntity(Long id) {
        QueryWrapper<GroupEntity> wrapper = new QueryWrapper<>();
        wrapper.apply("id = {0} and delete_flag = FALSE", id);
        return count(wrapper) > 0;
    }

    @Override
    public Boolean updateProductGroup(Long id, GroupEntity entity, Long updateId) {
        return update(entity, "id = {0}", id);
    }
}
